package com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzxczh.base.dict.service.DictService;
import com.css.fxfzxczh.base.remote.RemoteService;
import com.css.fxfzxczh.base.response.RestResponse;
import com.css.fxfzxczh.constants.FxfzConstants;
import com.css.fxfzxczh.modules.boundary.repository.BoundaryRepository;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.*;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.jcsj.JcIntensity;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.ypg.BuildingVulnerability;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.ypg.DataPbeInjuries;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.ypg.DataPbeIntStrArea;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.ypg.VulnerabilityVO;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.ysx.EstimateParam;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.entity.ysx.GenerateVulnerabilityMatrixVo;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.param.EvaluateParam;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.param.ModelParam;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.param.SysDataVersionPageParam;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.repository.AreaRatioRepository;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.repository.AssessmentVulnerabilityRepository;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.repository.CasualtiesRepository;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.vo.CountyIntensityVO;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.casualties.vo.PopulationVO;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.fastSeismicInfluence.service.IntensityAttenuationService;
import com.css.fxfzxczh.modules.fastDisasterAnalysis.houseDestroy.vo.DsGpbGdzVO;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import com.css.fxfzxczh.zcpt.sys.service.SysAreaService;
import com.css.fxfzxczh.zcpt.sys.service.SysRoleService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年07月26日  14:17
 */
@Service
public class CasualtiesService {
    @Resource
    CasualtiesRepository casualtiesRepository;
    @Resource
    IntensityAttenuationService intensityAttenuationService;
    @Resource
    RemoteService remoteService;
    @Value("${fxfzypg.url}")
    private String fxfzypgUrl;
    @Value("${jcsj.url}")
    private String jcsjUrl;
    @Resource
    SUserService sUserService;
    @Resource
    SysAreaService sysAreaService;
    public static final int BATCH_SIZE = 100000;
    @Resource
    BoundaryRepository boundaryRepository;
    @Resource
    SysRoleService sysRoleService;

    @Resource
    AssessmentVulnerabilityRepository assessmentVulnerabilityRepository;
    @Resource
    AreaRatioRepository areaRatioRepository;

    @Resource
    EarEveManageService earEveManageService;

    @Resource
    DictService dictService;
    @Transactional(rollbackFor = Exception.class)
    public void evaluate(EvaluateParam param) throws Exception{
        //先删除模型数据
        casualtiesRepository.deletePopulationEvaluateModel(param.getXsemId());
        //删除评估结果
        casualtiesRepository.deletePopulationEvaluateResult(param.getXsemId());
//        //根据任务id获取任务下的所有的影响场（椭圆）下的同一个地震烈度的格网的人员伤亡数据
//        List<Map<String, Object>> mapList = casualtiesRepository.getPbeInjuriesByXsemId(param.getXsemId());
//        if (PlatformObjectUtils.isEmpty(mapList)) {
//            throw new RuntimeException("计算失败,该任务尚未生成影响场!");
//        }
//        //获取到同一个设定地震点下不同影响场的最大相交面积的格网的数据
//        Map<String, Map<String, Object>> initMap = initMap(mapList);
//        Map<String, Object[]> resultMap = getSumBySeismicInfluenceAndCounty(initMap);

        List<CountyIntensityVO> countyIntensity = casualtiesRepository.getCountyIntensity(param.getXsemId(), param.getFvId());
        //查询影响场范围内的格网的人员伤亡信息
        List<DataPbeInjuries> list=new ArrayList<>();
        for(CountyIntensityVO item:countyIntensity){
            List<DataPbeInjuries> PbeInjurieslist=casualtiesRepository.getPbeInjuriesByXsemIdAndCodeAndIntensities(param.getXsemId(),item.getCode(), Arrays.asList(item.getIntensities().split(",")));
            list.addAll(PbeInjurieslist);
        }

        //List<DataPbeInjuries> pbeInjuries = casualtiesRepository.getPbeInjuriesByXsemId(param.getXsemId());
        //保存模型信息
        String xfpemId = saveEvaluateModel(param);
        //保存评估结果
        saveEvaluateResult(list,param.getXsemId(),xfpemId);
    }

    private String saveEvaluateModel(EvaluateParam param) throws Exception{
        String xfpemId = UUIDGenerator.getUUID();
        PopulationEvaluateModel model = new PopulationEvaluateModel();
        model.setXfpemId(xfpemId).setBuildingVersion(param.getBuildingVersion()).setPopulationVersion(param.getPopulationVersion())
                .setInfluenceVersion(param.getInfluenceVersion()).setFvId(param.getFvId()).setModelId(param.getModelId())
                .setEvaluateUser(PlatformSessionUtils.getUserId()).setEvaluateTime(new Date()).setXsemId(param.getXsemId());
        if(!casualtiesRepository.saveEvaluateModel(model)){
           throw new RuntimeException("评估模型保存失败");
        }
        return xfpemId;
    }

    private void saveEvaluateResult(List<DataPbeInjuries> pbeInjuries,String xsemId,String xfpemId) {
        List<PopulationEvaluateResult> resultList = new ArrayList<>();
        //以省市县为单位进行分组
        Map<String, List<DataPbeInjuries>> collect = pbeInjuries.stream().collect(Collectors.groupingBy(dataPbeInjuries -> dataPbeInjuries.getProvince() + "_" + dataPbeInjuries.getCity() + "_" + dataPbeInjuries.getCounty()));
        collect.forEach((k,v)->{
            String[] split = k.split("_");
            PopulationEvaluateResult result = new PopulationEvaluateResult();
            BigDecimal deathNum = v.stream().filter(dataPbeInjuries -> PlatformObjectUtils.isNotEmpty(dataPbeInjuries.getDeathNum())).map(DataPbeInjuries::getDeathNum).reduce(BigDecimal.ZERO, BigDecimal::add);
            result.setXfperId(UUIDGenerator.getUUID()).setXsemId(xsemId);
            result.setProvince(split[0]).setCity(split[1]).setCounty(split[2]);
            result.setProvinceCode(v.get(0).getProvinceCode()).setCityCode(v.get(0).getCityCode()).setCountyCode(v.get(0).getCountyCode());
            BigDecimal injuriesNum = v.stream().filter(dataPbeInjuries -> PlatformObjectUtils.isNotEmpty(dataPbeInjuries.getInjuriesNum())).map(DataPbeInjuries::getInjuriesNum).reduce(BigDecimal.ZERO, BigDecimal::add);
            //获取死亡人数所属区间
            String deathNumRange = getDeathNumRange(deathNum);
            //获取受伤人数所属区间
            String injuriesNumRange = getInjuriesNumRange(injuriesNum);
            result.setDeathNum(deathNum+"").setDeathNumRange(deathNumRange).setInjuriesNum(injuriesNum+"").setInjuriesNumRange(injuriesNumRange);
            result.setXfpemId(xfpemId);
            //查询区县的空间数据
            //BoundaryEntity bundaryEntityByCode = boundaryRepository.getBundaryEntityByCode(v.get(0).getCountyCode(), "3");
            String geom = casualtiesRepository.getUnionGeom(split[0].toString(),split[1].toString(),split[2].toString(),xsemId);
            result.setGeom(geom);
            resultList.add(result);
        });
        if(resultList.size()>0){
            casualtiesRepository.batchSave(resultList);
        }
    }

    private String getInjuriesNumRange(BigDecimal injuriesNum) {
        BigDecimal temp = injuriesNum;
        String result = "";
        if(temp.compareTo(new BigDecimal(10))<=0){
            result = (0+"-"+10);
        }else if(temp.compareTo(new BigDecimal(50))<=0){
            result = (10+"-"+50);
        }else if(temp.compareTo(new BigDecimal(100))<=0){
            result = (50+"-"+100);
        }else if(temp.compareTo(new BigDecimal(500))<=0){
            result = (100+"-"+500);
        }else if(temp.compareTo(new BigDecimal(500))>0){
            result = ("500以上");
        }
        return result;
    }

    private String getDeathNumRange(BigDecimal deathNum) {
        BigDecimal temp = deathNum;
        String result = "";
        if(temp.compareTo(new BigDecimal(10))<=0){
            result = (0+"-"+10);
        }else if(temp.compareTo(new BigDecimal(30))<=0){
            result = (10+"-"+30);
        }else if(temp.compareTo(new BigDecimal(50))<=0){
            result = (30+"-"+50);
        }else if(temp.compareTo(new BigDecimal(100))<=0){
            result = (50+"-"+100);
        }else if(temp.compareTo(new BigDecimal(300))<=0){
            result = (100+"-"+300);
        }else if(temp.compareTo(new BigDecimal(500))<=0){
            result = (300+"-"+500);
        }else if(temp.compareTo(new BigDecimal(500))>0){
            result = ("500以上");
        }
        return result;
    }

    //求每个烈度下的各个区县下的死亡人数和和受伤人数和
    private Map<String, Object[]> getSumBySeismicInfluenceAndCounty(Map<String, Map<String, Object>> initMap){
        Map<String, Object[]> detailMap = new HashMap<>();
        for (Map.Entry<String, Map<String, Object>> entry : initMap.entrySet()) {
            Map<String, Object> value = entry.getValue();
            Object[] objects = null;
            String key1 =  value.get("fsiId") + "-" + value.get("province") + "-" +
                    value.get("city") + "-" + value.get("county");
            if (detailMap.containsKey(key1)) {
                objects = detailMap.get(key1);
                objects[0] = new BigDecimal(objects[0].toString()).add(BigDecimal.valueOf((Double) value.get("deathNum")));//受伤人数和
                objects[1] = new BigDecimal(objects[1].toString()).add(BigDecimal.valueOf((Double) value.get("injuriesNum")));//死亡人数和
            } else {
                //初始化
                objects = new Object[5];
                objects[0] = BigDecimal.valueOf((Double) value.get("deathNum"));
                objects[1] = BigDecimal.valueOf((Double) value.get("injuriesNum"));
                objects[2] = value.get("provinceCode");
                objects[3] = value.get("cityCode");
                objects[4] = value.get("countyCode");
            }
            detailMap.put(key1, objects);
        }
        return detailMap;
    }

    private Map<String, Map<String, Object>> initMap(List<Map<String, Object>> mapList) {
        //pbeId,area,deathNum,injuriesNum,longitude,latitude,earthquakeLevel,angle,earthquakeId
        Map<String, Map<String, Object>> initMap = new HashMap<>();
        for (Map<String, Object> map1 : mapList) {
            String key = map1.get("pbeId")+"-"+map1.get("fsiId");
            if (initMap.containsKey(key)) {
                Map<String, Object> map2 = initMap.get(key);
                if (((Double) map2.get("area")).compareTo((Double) map1.get("area")) < 0) {
                    initMap.put(key, map1);
                }else if (((Double) map2.get("area")).compareTo((Double) map1.get("area")) == 0) {
                    if (((Double) map2.get("earthquakeLevel")).compareTo((Double) map1.get("earthquakeLevel"))<0){
                        initMap.put(key, map1);
                    }
                }
            } else {
                initMap.put(key, map1);
            }
        }
        return initMap;
    }

    @Transactional(rollbackFor = Exception.class)
    public RestResponse countIntensityAndStructureOfArea(EvaluateParam evaluateParam) throws Exception{
        Long start = System.currentTimeMillis();
        String xsemId = evaluateParam.getXsemId();
        String buildingVersion = evaluateParam.getBuildingVersion();
        String populationVersion = evaluateParam.getPopulationVersion();
        String sign = evaluateParam.getSign();

        casualtiesRepository.deleteAssessmentVulnerability(xsemId,buildingVersion,populationVersion);
        //删除taskId上一次计算的结果
        casualtiesRepository.deleteDataPbeIntStrAreaByXsemId(evaluateParam.getXsemId());
        //获取同一地震事件下的所有影响场空间数据的并集
        String unionGeom = intensityAttenuationService.getUnionGeom(evaluateParam.getXsemId());
        if(StringUtils.isBlank(unionGeom)){
            throw new RuntimeException("评估失败,该地震事件下查询不到影响场信息");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("buildingVersion",evaluateParam.getBuildingVersion());
        jsonObject.put("populationVersion",evaluateParam.getPopulationVersion());
        jsonObject.put("geom",unionGeom);
        //远程调用基础数据系统接口获取建筑物和人口指定版本的格网信息
        System.out.println("获取人口网格数据开始");
        //final String url  = jcsjUrl+"/datacenter/jcPopulationGrid/getPopulationAndDsGpbGdz";
        final String url  = jcsjUrl+"/datacenter/jcPopulationGrid/getPopulation";
        JSONArray jsonArray =  null;
        Long getGridStart = System.currentTimeMillis();
        try{
            jsonArray =  (JSONArray) remoteService.getJCSJ(url, 4, jsonObject).getData();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException("评估失败，无法获取人口格网数据");
        }
        Long getGridEnd = System.currentTimeMillis();
        System.out.println("远程基础数据获取人口格网数据所花费的时间为:"+(getGridEnd-getGridStart)/1000);
        List<PopulationVO> populationVOS = JSONObject.parseArray(jsonArray.toJSONString(), PopulationVO.class);
        Map<String, PopulationVO> popCollectMap = populationVOS.stream().filter(Objects::nonNull).collect(Collectors.toMap(PopulationVO::getExtends1, Function.identity()));
        System.out.println("获取房屋网格数据开始");
        final String houseUrl  = jcsjUrl+"/datacenter/jcPopulationGrid/getDsGpbGdz";
        JSONArray houseJsonArray =  null;
        Long getHouseGridStart = System.currentTimeMillis();
        try{
            houseJsonArray =  (JSONArray) remoteService.getJCSJ(houseUrl, 4, jsonObject).getData();
        }catch (Exception ex){
            ex.printStackTrace();
            throw new RuntimeException("评估失败，无法获取房屋格网数据");
        }
        Long getHouseGridEnd = System.currentTimeMillis();
        System.out.println("远程基础数据获取房屋格网数据所花费的时间为:"+(getHouseGridEnd-getHouseGridStart)/1000);
        if (PlatformObjectUtils.isEmpty(houseJsonArray) || houseJsonArray.size()==0){
            throw new RuntimeException("评估失败,请先维护基础数据的建筑物格网数据");
        }
        List<DsGpbGdzVO> DsGpbGdzVOs = JSONObject.parseArray(houseJsonArray.toJSONString(), DsGpbGdzVO.class);

        DsGpbGdzVOs = DsGpbGdzVOs.stream().filter(dsGpbGdzVO -> StringUtils.isNotBlank(dsGpbGdzVO.getExtends1())).collect(Collectors.toList());
        if(DsGpbGdzVOs==null || DsGpbGdzVOs.size()==0){
            throw new RuntimeException("计算未完成，请到数据管理系统维护建筑物格网信息");
        }
        Map<String, DsGpbGdzVO> houseCollectMap = DsGpbGdzVOs.stream().filter(Objects::nonNull).collect(Collectors.toMap(DsGpbGdzVO::getExtends1, Function.identity()));

        List<PopulationAndDsGpbGdzVo> gridList = new ArrayList<>();
        houseCollectMap.forEach((k,v)->{
            PopulationVO populationVO = popCollectMap.get(k);
            PopulationAndDsGpbGdzVo vo = new PopulationAndDsGpbGdzVo();
            BeanUtils.copyProperties(v,vo);
            if(PlatformObjectUtils.isNotEmpty(populationVO)){
                BeanUtils.copyProperties(populationVO,vo);
            }else{
               vo.setTotalArea(0.0);
               vo.setHousecount(0);
               vo.setSteelratio(0.0);
               vo.setReconratio(0.0);
               vo.setBrickratio(0.0);
               vo.setWoodratio(0.0);
               vo.setOtherratio(0.0);
               vo.setGeom(v.getGeom());
            }
            vo.setExtends1(k);
            gridList.add(vo);
        });
        //key:地震烈度；value:建筑物易损性信息VO
        Map<String, List<VulnerabilityVO>> listMap = null;


        List<BuildingVulnerability> vulnerabilityList = new ArrayList<>();
        //建筑物易损性信息
        List<BuildingVulnerability> allVulnerability = new ArrayList<>();

        //格网数据
        List<DataPbeIntStrArea> pbeIntStrAreaList = new ArrayList<>();
        Map<String,List<BuildingVulnerability>> map = new HashMap<>();
        for (PopulationAndDsGpbGdzVo grid : gridList) {
            //每个格网的建筑物面积
            Double area = grid.getTotalArea();
            if(PlatformObjectUtils.isEmpty(area)){
                continue;
            }
            //每个格网的建筑面积
            BigDecimal totalArea = BigDecimal.valueOf(area);
            //钢结构建筑面积百分比(小数)
            BigDecimal steelRatio = PlatformObjectUtils.isEmpty(grid.getSteelratio()) || grid.getSteelratio()==0.0?BigDecimal.ZERO:(BigDecimal.valueOf(grid.getSteelratio()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
            //钢筋混凝土结构建筑面积百分比(小数)
            BigDecimal reconRatio = PlatformObjectUtils.isEmpty(grid.getReconratio()) || grid.getReconratio()==0.0 ?BigDecimal.ZERO:(BigDecimal.valueOf(grid.getReconratio()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
            //砖混结构建筑面积百分比(小数)
            BigDecimal brickRatio = PlatformObjectUtils.isEmpty(grid.getBrickratio()) || grid.getBrickratio()==0.0?BigDecimal.ZERO:(BigDecimal.valueOf(grid.getBrickratio()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
            //木结构建筑面积百分比(小数)
            BigDecimal woodRatio = PlatformObjectUtils.isEmpty(grid.getWoodratio()) || grid.getWoodratio()==0.0?BigDecimal.ZERO:(BigDecimal.valueOf(grid.getWoodratio()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));
            //其他结构建筑面积百分比(小数)
            BigDecimal otherRatio = PlatformObjectUtils.isEmpty(grid.getOtherratio()) || grid.getOtherratio()==0.0?BigDecimal.ZERO:(BigDecimal.valueOf(grid.getOtherratio()).divide(BigDecimal.valueOf(100), 10, BigDecimal.ROUND_UP));

            //获取五种结构类型的面积  总面积*各个结构类型所占的比列
            //钢结构建筑面积
            BigDecimal steelArea = totalArea.multiply(steelRatio);
            //钢筋混凝土结构建筑面积
            BigDecimal reconArea = totalArea.multiply(reconRatio);
            //砖混结构建筑面积
            BigDecimal brickArea = totalArea.multiply(brickRatio);
            //木结构建筑面积
            BigDecimal woodArea = totalArea.multiply(woodRatio);
            //其他结构建筑面积
            BigDecimal otherArea = totalArea.multiply(otherRatio);

            //查询建筑物易损性数据 每个省市县只查询一次数据库
            if(map.containsKey(grid.getProvince()+"-"+grid.getCity()+"-"+grid.getCounty())){
                allVulnerability = map.get(grid.getProvince()+"-"+grid.getCity()+"-"+grid.getCounty());
            }else{
                if ("1".equals(sign)){
                    long start1 = System.currentTimeMillis();
                    //获取承载体系统易损性数据
                    allVulnerability = getAllVulnerabilityList(grid.getProvince(),grid.getCity(),grid.getCounty());
                    long end = System.currentTimeMillis();

                    System.out.println("易损性计算花费" + (end - start1) / 1000);
                }else {
                    Long getVulnerabilityStart = System.currentTimeMillis();
                    allVulnerability  = getBuildingGridDataVersionList(grid);
                    System.out.println("远程ypg获取建筑物易损性数据花费时间为:"+(System.currentTimeMillis()-getVulnerabilityStart)/1000);
//                if(PlatformObjectUtils.isEmpty(allVulnerability) || allVulnerability.size()==0){
//                    continue;
//                    //throw new RuntimeException("评估失败，请到预评估系统维护"+grid.getProvince()+"-"+grid.getCity()+"-"+grid.getCounty()+"的建筑物易损性数据");
//                }
                }





                vulnerabilityList.addAll(allVulnerability);
                map.put(grid.getProvince()+"-"+grid.getCity()+"-"+grid.getCounty(),allVulnerability);
            }
            if(allVulnerability.size()>0){
                //改造allVulnerability <烈度,[{结构类型，破坏程度，比例}]>
                Map<String, Object> rebuild = rebuild(allVulnerability);
                if (!rebuild.get("code").equals("200")) {
                    throw new RuntimeException(String.valueOf(rebuild.get("msg")));
                }
                listMap = (Map<String, List<VulnerabilityVO>>) rebuild.get("listMap");
            }
            for (int i = 6; i < 11; i++) {
                if (PlatformObjectUtils.isNotEmpty(allVulnerability)) {
                    //[{结构类型，破坏程度，比例}] 高层结构 在基本完好时的比例
                    if(listMap!=null){
                        List<VulnerabilityVO> vulnerabilityVOS = listMap.get(String.valueOf(i));
                        if(PlatformObjectUtils.isNotEmpty(vulnerabilityVOS)){
                            for (VulnerabilityVO vo : vulnerabilityVOS) {
                                //各种建筑结构在不同破坏程度下的破坏面积
                                BigDecimal tsteelArea = steelArea.multiply(vo.getZero());
                                BigDecimal treconArea = reconArea.multiply(vo.getOne());
                                BigDecimal tbrickArea = brickArea.multiply(vo.getTwo());
                                BigDecimal twoodArea = woodArea.multiply(vo.getThree());
                                BigDecimal totherArea = otherArea.multiply(vo.getFour());
                                DataPbeIntStrArea pbeIntStrArea = new DataPbeIntStrArea();
                                pbeIntStrArea.setId(UUIDGenerator.getUUID()).setPbeId(grid.getId())
                                        .setDzIntensity(String.valueOf(i)).setXsemId(evaluateParam.getXsemId()).setGeom(grid.getGeom())
                                        .setSteelArea(tsteelArea).setCArea(treconArea).setBArea(tbrickArea).setWArea(twoodArea).setOArea(totherArea)
                                        .setDestroy(vo.getDestroy()).setPopulation(BigDecimal.valueOf(grid.getTzl3()))
                                        .setCoveredArea(BigDecimal.valueOf(area)).setProvince(grid.getProvince())
                                        .setCity(grid.getCity()).setCounty(grid.getCounty()).setTown(grid.getTown())
                                        .setProvinceCode(String.valueOf(grid.getFxpcXzqhb())).setCityCode(String.valueOf(grid.getFxpcXz01()))
                                        .setCountyCode(String.valueOf(grid.getFxpcXz02()));
                                pbeIntStrAreaList.add(pbeIntStrArea);
                            }
                        }
                    }
                } else {
                    for (int j = 0; j < 5; j++) {
                        DataPbeIntStrArea pbeIntStrArea = new DataPbeIntStrArea();
                        pbeIntStrArea.setId(UUIDGenerator.getUUID()).setPbeId(grid.getId())
                                .setDzIntensity(String.valueOf(i)).setXsemId(evaluateParam.getXsemId()).setGeom(grid.getGeom())
                                .setSteelArea(BigDecimal.ZERO).setCArea(BigDecimal.ZERO).setBArea(BigDecimal.ZERO).setWArea(BigDecimal.ZERO).setOArea(BigDecimal.ZERO)
                                .setDestroy(String.valueOf(j)).setPopulation(BigDecimal.valueOf(grid.getTzl3()))
                                .setCoveredArea(BigDecimal.valueOf(area)).setProvince(grid.getProvince())
                                .setCity(grid.getCity()).setCounty(grid.getCounty()).setTown(grid.getTown())
                                .setProvinceCode(String.valueOf(grid.getFxpcXzqhb())).setCityCode(String.valueOf(grid.getFxpcXz01()))
                                .setCountyCode(String.valueOf(grid.getFxpcXz02()));;
                        pbeIntStrAreaList.add(pbeIntStrArea);
                    }
                }
            }
        }
        System.out.println(pbeIntStrAreaList.size()+ "开始插入");
        //一次10万条
        int fromIndex = 0; int toIndex = BATCH_SIZE;
        while (fromIndex != pbeIntStrAreaList.size()) {
            if (toIndex > pbeIntStrAreaList.size()) {
                toIndex = pbeIntStrAreaList.size();
            }
            List<DataPbeIntStrArea> list = pbeIntStrAreaList.subList(fromIndex, toIndex);
            int insertcount = casualtiesRepository.batchupdate(list);
            System.out.println("插入成功"+insertcount );
            fromIndex = toIndex;
            toIndex += BATCH_SIZE;
            if (toIndex > pbeIntStrAreaList.size()){
                toIndex = pbeIntStrAreaList.size();
            }
        }
        System.out.println("保存格网时间花费" + (System.currentTimeMillis() - start) / 1000);

        //保存易损性数据，用于查看
        List<AssessmentVulnerability> list = vulnerabilityList.stream()
                .map(bv -> new AssessmentVulnerability(
                        UUIDGenerator.getUUID(),
                        bv.getProvince(),
                        bv.getCity(),
                        bv.getPrefecture(),
                        bv.getStructureType(),
                        bv.getDestroy(),
                        bv.getSix(),
                        bv.getSeven(),
                        bv.getEight(),
                        bv.getNine(),
                        bv.getTen(),
                        xsemId,
                        sign,
                        buildingVersion,
                        populationVersion
                ))
                .collect(Collectors.toList());
        assessmentVulnerabilityRepository.batchSave(list);
        return ResponseCreator.createSuccessResponse("计算成功!");
    }




    private List<BuildingVulnerability> getAllVulnerabilityList(String province, String city, String county) {
        List<BuildingVulnerability> vulnerabilityList = new ArrayList<>();
        //从基础数据获取该县的设防情况
        String url = jcsjUrl+"/datacenter/sysDataVersion/xczh/getIntensityByCondition?province="+province+"&city="+city+"&county="+county+"";

        Object jcIntensityData = remoteService.getJCSJ(url, 2, new JSONObject()).getData();
        if(jcIntensityData==null){
            throw new RuntimeException("评估失败，系统未获取到"+province+"-"+city+"-"+county+"的设防烈度数据请到数据管理系统-房屋-设防烈度数据中进行维护");
        }
        JSONObject object = (JSONObject) jcIntensityData;
        JcIntensity jcIntensity = JSON.parseObject(object.toJSONString(), JcIntensity.class);


        //查询该县是否自定义面积配比，有则使用
        List<AreaRatio> areaRatioList =areaRatioRepository.getAreaRatioByCondition(province, city, county);
        List<EstimateParam> estimateParamList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(areaRatioList)) {

            for (AreaRatio areaRatio : areaRatioList) {
                EstimateParam estimateParam = new EstimateParam();
                BeanUtils.copyProperties(areaRatio, estimateParam);
                estimateParam.setYearsList(Arrays.stream(areaRatio.getYear().split(",")).map(BigDecimal::new).collect(Collectors.toList()));
                estimateParam.setUseList(Arrays.stream(areaRatio.getUse().split(",")).map(BigDecimal::new).collect(Collectors.toList()));
                estimateParam.setCsList(Arrays.stream(areaRatio.getCs().split(",")).map(BigDecimal::new).collect(Collectors.toList()));
                estimateParamList.add(estimateParam);
            }
        } else {

            EstimateParam estimateParam = new EstimateParam();
            estimateParam.setProvince(province);
            estimateParam.setCity(city);
            estimateParam.setCounty(county);
            estimateParamList.add(estimateParam);

        }

        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String ysxUrl = configGroup.getProperty("ysxRestUrl") + "/customVulnerability/getByRegion";
        JSONObject valueMap = new JSONObject();
        valueMap.put("list", estimateParamList);
        valueMap.put("fortification",jcIntensity.getIntensity());

        Object data = remoteService.getJCSJ(ysxUrl, 6, valueMap).getData();
        if(!Objects.isNull(data)){
            JSONArray jsonArray = (JSONArray) data;
            vulnerabilityList = JSON.parseArray(jsonArray.toJSONString(), BuildingVulnerability.class);
            for (BuildingVulnerability buildingVulnerability : vulnerabilityList) {
                buildingVulnerability.setDestroy(transformation(buildingVulnerability.getDestroy()));

            }

            // 定义 Comparator 接口按照 destroy 字段和 structureType 字段排序
            Comparator<BuildingVulnerability> comparator = Comparator
                    .comparingInt((BuildingVulnerability test) -> Integer.parseInt(test.getDestroy()))
                    .thenComparing((BuildingVulnerability test) -> Integer.parseInt(test.getStructureType()));


            // 对 vulnerabilityList 使用定义好的比较器进行排序
            Collections.sort(vulnerabilityList, comparator);
//            for (BuildingVulnerability buildingVulnerability : vulnerabilityList) {
//                System.out.println(buildingVulnerability);
//
//            }

        }

        return vulnerabilityList;
    }

    /**
     *  * 0基本完好
     *      * 1轻微破坏
     *      * 2中等破坏
     *      * 3严重破坏
     *      * 4损坏
     * @param destroy
     * @return
     */
    private String transformation(String destroy) {
        if ("基本完好".equals(destroy)) {
            destroy = "0";
        }
        if ("轻微破坏".equals(destroy)) {
            destroy = "1";
        }
        if ("中等破坏".equals(destroy)) {
            destroy = "2";
        }
        if ("严重破坏".equals(destroy)) {
            destroy = "3";
        }
        if ("倒塌".equals(destroy)) {
            destroy = "4";
        }


        return destroy;
    }
    private Map<String, Object> rebuild(List<BuildingVulnerability> allVulnerability) {
        Map<String, Object> map = null;
        List<String> list = new ArrayList<>();//存储 结构类型+破坏程度，用以判断是否重复
        Map<String, List<VulnerabilityVO>> listMap = new HashMap<>();
        List<VulnerabilityVO> voList1 = null;
        List<VulnerabilityVO> voList2 = null;
        List<VulnerabilityVO> voList3 = null;
        List<VulnerabilityVO> voList4 = null;
        List<VulnerabilityVO> voList5 = null;
        //只计算钢结构、多层钢筋混凝土、砖混、木和其他结构的
        for (int i = 0; i < allVulnerability.size(); ) {
            BuildingVulnerability buildingVulnerability1 = allVulnerability.get(i);
            BuildingVulnerability buildingVulnerability2 = allVulnerability.get(i+1);
            BuildingVulnerability buildingVulnerability3 = allVulnerability.get(i+2);
            BuildingVulnerability buildingVulnerability4 = allVulnerability.get(i+3);
            BuildingVulnerability buildingVulnerability5 = allVulnerability.get(i+4);
            VulnerabilityVO vo = new VulnerabilityVO();

            if (listMap.containsKey("6")) {
                voList1 = listMap.get("6");
            } else {
                voList1 = new ArrayList<>();
            }
            String destroy = buildingVulnerability1.getDestroy();
            vo.setDestroy(destroy);
            if ("1".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getSix());
                i++;
            }

            if ("2".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getSix());
                i++;
            }

            if ("3".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getSix());
                i++;
            }

            if ("6".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getSix());
                i++;
            }

            if ("8".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "6", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getSix());
                i++;
            }
            voList1.add(vo);
            listMap.put("6", voList1);

            //烈度7
            if (listMap.containsKey("7")) {
                voList2 = listMap.get("7");
            } else {
                voList2 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("1".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getSeven());
            }

            if ("2".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getSeven());
            }

            if ("3".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getSeven());
            }

            if ("6".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getSeven());
            }

            if ("8".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "7", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getSeven());
            }
            voList2.add(vo);
            listMap.put("7", voList2);

            //烈度8
            if (listMap.containsKey("8")) {
                voList3 = listMap.get("8");
            } else {
                voList3 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("1".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getEight());
            }

            if ("2".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getEight());
            }

            if ("3".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getEight());
            }

            if ("6".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getEight());
            }

            if ("8".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "8", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getEight());
            }
            voList3.add(vo);
            listMap.put("8", voList3);

            //烈度9
            if (listMap.containsKey("9")) {
                voList4 = listMap.get("9");
            } else {
                voList4 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("1".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getNine());
            }

            if ("2".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getNine());
            }

            if ("3".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getNine());
            }

            if ("6".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getNine());
            }

            if ("8".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "9", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getNine());
            }
            voList4.add(vo);
            listMap.put("9", voList4);

            //烈度10
            if (listMap.containsKey("10")) {
                voList5 = listMap.get("10");
            } else {
                voList5 = new ArrayList<>();
            }
            vo = new VulnerabilityVO();
            vo.setDestroy(destroy);
            if ("1".equals(buildingVulnerability1.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability1.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setZero(buildingVulnerability1.getTen());
            }

            if ("2".equals(buildingVulnerability2.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability2.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setOne(buildingVulnerability2.getTen());
            }

            if ("3".equals(buildingVulnerability3.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability3.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setTwo(buildingVulnerability3.getTen());
            }

            if ("6".equals(buildingVulnerability4.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability4.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setThree(buildingVulnerability4.getTen());
            }

            if ("8".equals(buildingVulnerability5.getStructureType())) {
                map = isRepeat(list, "10", buildingVulnerability5.getStructureType(), destroy);
                if (map != null) {
                    return map;
                }
                vo.setFour(buildingVulnerability5.getTen());
            }
            voList5.add(vo);
            listMap.put("10", voList5);
        }
        map = new HashMap<>();
        map.put("code", "200");
        map.put("listMap", listMap);
        return map;
    }

    private Map<String, Object> isRepeat(List<String> list, String dzIntensity, String structureType, String destroy) {
        Map<String, Object> map = new HashMap<>();
        if (list.contains(dzIntensity + "-" + structureType + "-" + destroy)) {
            map.put("code", "500");
            switch (structureType) {
                case "0":
                    structureType = "高层结构";
                    break;
                case "1":
                    structureType = "钢结构";
                    break;
                case "2":
                    structureType = "混凝土结构";
                    break;
                case "3":
                    structureType = "砖混结构";
                    break;
                case "4":
                    structureType = "砖木结构";
                    break;
                case "5":
                    structureType = "土结构";
                    break;
                case "6":
                    structureType = "木结构";
                    break;
                case "7":
                    structureType = "石结构";
                    break;
                case "8":
                    structureType = "其他结构";
                    break;
            }
            switch (destroy) {
                case "0":
                    destroy = "基本完好";
                    break;
                case "1":
                    destroy = "轻微破坏";
                    break;
                case "2":
                    destroy = "中等破坏";
                    break;
                case "3":
                    destroy = "严重破坏";
                    break;
                case "4":
                    destroy = "毁坏";
                    break;
            }
            map.put("msg", "建筑物易损性烈度为" + dzIntensity + "的" + structureType + "的" + destroy + "的破坏程度的数据有异常！");
            return map;
        }
        list.add(dzIntensity + "-" + structureType + "-" + destroy);
        return null;
    }

    private List<BuildingVulnerability> getBuildingGridDataVersionList(PopulationAndDsGpbGdzVo grid) throws Exception {
        final String ypgUrl = fxfzypgUrl+"/buildingVulnerability/remoteGetAllVulnerabilityOrder?province="+grid.getProvince()+"&city="+grid.getCity()+"&county="+grid.getCounty()+"&source="+"1,2,3,6,8";
        JSONObject valueMap = new JSONObject();
        Object data = remoteService.getJCSJ(ypgUrl, 3, valueMap).getData();
        if(data==null){
            return null;
            //throw new RuntimeException("评估失败，查询不到"+grid.getProvince()+"-"+grid.getCity()+"-"+grid.getCounty()+"下的建筑物易损性数据");
        }
        JSONArray jsonArray = (JSONArray) data;
        return  JSON.parseArray(jsonArray.toJSONString(), BuildingVulnerability.class);
    }
    private String getAreaId(SUser sUser) throws Exception{
        if(sUser==null){
            throw new RuntimeException("评估失败，查询不到登录者信息");
        }
        StringBuilder areaId = new StringBuilder();
        if(StringUtils.isBlank(sUser.getProvinceId())){
            throw new RuntimeException("评估失败，查询不到登录者所属省信息");
        }
        areaId.append(sUser.getProvinceId());
        if(StringUtils.isNotBlank(sUser.getCityId())){
            areaId.append(",").append(sUser.getCityId());
        }
        if(StringUtils.isNotBlank(sUser.getCountyId())){
            areaId.append(",").append(sUser.getCountyId());
        }
        return areaId.toString();
    }

    //查询模型信息
    private Casualties getModelMessage(String modelId) {
        String url = fxfzypgUrl + "/casualty/getModelById?id=" + modelId;
        Object data = remoteService.getJCSJ(url, 2, new JSONObject()).getData();
        if(data!=null){
            return  JSONObject.parseObject(((JSONObject)data).toJSONString(), Casualties.class);
        }
       return null;
    }
    @Transactional(rollbackFor = Exception.class)
    public RestResponse savePbeInjuries(String modeId, String xsemId) {
        Long start = System.currentTimeMillis();
        //先删除之前生成的数据
        casualtiesRepository.deleteByXsemId(xsemId);
        //查询模型信息
        Casualties model = getModelMessage(modeId);
        if (PlatformObjectUtils.isEmpty(model)) {
            throw new RuntimeException("请选择人员伤亡模型");
        }
        @NotNull(message = "计算死亡人数系数不能为空") BigDecimal deathNumber = model.getDeathNumber();
        @NotNull(message = "受伤人数系数不能为空") BigDecimal injuries = model.getInjuries();
        //获取损坏程度的格网数据
        List<DataPbeIntStrArea> pbeList = casualtiesRepository.getDataPbeIntStrAreaByXsemId(xsemId, "4");
        List<DataPbeInjuries> pbeInjuriesList = new ArrayList<>();
        for (DataPbeIntStrArea entity : pbeList) {
            //每个格网的建筑物面积
            BigDecimal area = entity.getCoveredArea();
            //每个格网的人口数
            BigDecimal population = entity.getPopulation();

            //各种建筑物结构的房屋毁坏面积之和
            BigDecimal totalDanageArea = entity.getSteelArea().add(entity.getCArea()).add(entity.getBArea())
                    .add(entity.getWArea()).add(entity.getOArea());
            BigDecimal destroyPercent = BigDecimal.ZERO;
            if (area.compareTo(BigDecimal.ZERO) != 0) {
                //房屋毁坏比
                destroyPercent = totalDanageArea.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:totalDanageArea.divide(area, 8, BigDecimal.ROUND_HALF_UP);
            }
            double pow = Math.pow(destroyPercent.doubleValue(), 0.1);
            BigDecimal powBigdeciaml = new BigDecimal(pow);
            BigDecimal subtract = model.getSmrsNumber1().multiply(powBigdeciaml).subtract(model.getSmrsNumber2());
            double log = Math.pow(10, subtract.doubleValue());
            //死亡比
            BigDecimal deathRetio = new BigDecimal(log);
            //计算死亡人数
            BigDecimal deathPersonCount = deathNumber.multiply(population).multiply(deathRetio);
            //计算受伤人数
            BigDecimal injuryNum = deathPersonCount.multiply(injuries);
            DataPbeInjuries pbeInjuries = new DataPbeInjuries();
            pbeInjuries.setId(UUIDGenerator.getUUID()).setPbeId(entity.getPbeId()).setCoveredarea(area)
                    .setPopulation(entity.getPopulation().intValue()).setDeathNum(deathPersonCount.setScale(6, RoundingMode.HALF_UP))
                    .setDeath(deathNumber).setInjuriesNum(injuryNum.setScale(6, RoundingMode.HALF_UP)).setInjuries(injuries)
                    .setDzIntentity(entity.getDzIntensity()).setXsemId(xsemId).setGeomText(entity.getGeom())
                    .setProvince(entity.getProvince()).setCity(entity.getCity()).setCounty(entity.getCounty()).setTown(entity.getTown())
                    .setProvinceCode(entity.getProvinceCode()).setCityCode(entity.getCityCode())
                    .setCountyCode(entity.getCountyCode());
            pbeInjuriesList.add(pbeInjuries);
        }
        System.out.println("开始插入："+pbeInjuriesList.size());
        //一次10万条
        int fromIndex = 0; int toIndex = BATCH_SIZE;
        while (fromIndex != pbeInjuriesList.size()) {
            if (toIndex > pbeInjuriesList.size()) {
                toIndex = pbeInjuriesList.size();
            }
            List<DataPbeInjuries> list = pbeInjuriesList.subList(fromIndex, toIndex);
            int insertcount = casualtiesRepository.savepbeInjuriesList(list);
            System.out.println("插入成功"+insertcount );
            fromIndex = toIndex;
            toIndex += BATCH_SIZE;
            if (toIndex > pbeInjuriesList.size()){
                toIndex = pbeInjuriesList.size();
            }
        }
        System.out.println("保存格网时间花费" + (System.currentTimeMillis() - start) / 1000);
        return ResponseCreator.createSuccessResponse("计算成功!");
    }

    public RestResponse getVersion(SysDataVersionPageParam pageParam) {
        Integer hasNationwide = 1;
        String userId = PlatformSessionUtils.getUserId();
        String user = sUserService.getSUser(userId);
        if(PlatformObjectUtils.isEmpty(user)){
            return ResponseCreator.createFailResponse("查询不到用户信息");
        }
        String province = "";
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        StringBuilder str=new StringBuilder("");
        for(Map roleMap:roleMaps){
            str.append(roleMap.get("roleCode")+",");
        }
        String roles = str.toString();
        if(roles.contains(FxfzConstants.XCZH_PROVINCE_ROLE)){
            province = sUser.getProvinceId();
        }
        pageParam.setProvince(province);
        pageParam.setHasNationwide(hasNationwide);
        String url = jcsjUrl + "/datacenter/sysDataVersion/page?dataType2="+pageParam.getDataType2();
//        if("138".equals(pageParam.getDataType2())){
//            url+="&dataType=54";
//        }
        if(pageParam.getUploadStartTime()!=null){
            url += "&uploadStartTime="+pageParam.getUploadStartTime();
        }
        if(pageParam.getUploadEndTime()!=null){
            url += "&uploadEndTime="+pageParam.getUploadEndTime();
        }
        if(pageParam.getUploadUsername()!=null){
            url += "&uploadUsername="+pageParam.getUploadUsername();
        }
        if(pageParam.getVersionDesc()!=null){
            url += "&versionDesc="+pageParam.getVersionDesc();
        }
        url += "&page="+pageParam.getPage()+"&rows="+pageParam.getRows()+"&hasNationwide="+hasNationwide;
        return remoteService.getJCSJ(url,2,new JSONObject());
    }

    public RestResponse chooseModel(ModelParam modelParam) {

        String url = fxfzypgUrl + "/casualty/pageForXczh?page="+modelParam.getPage()+"&rows="+modelParam.getRows();
        if(modelParam.getProvince()!=null){
            url += "&province="+modelParam.getProvince();
        }
        if(modelParam.getCity()!=null){
            url += "&city="+modelParam.getCity();
        }
        if(modelParam.getModelName()!=null){
            url += "&modelName="+modelParam.getModelName();
        }
        return remoteService.getJCSJ(url,2,new JSONObject());
    }

    public RestResponse getPopulationResult(String xsemId) {
        List<PopulationEvaluateResult> populationEvaluateResults = casualtiesRepository.getPopulationResult(xsemId);
        return ResponseCreator.createSuccessResponse(populationEvaluateResults);
    }

    public  RestResponse getModelData(String xsemId) {
        PopulationEvaluateModel model = casualtiesRepository.getModelData(xsemId);
        if(PlatformObjectUtils.isNotEmpty(model) && PlatformObjectUtils.isNotEmpty(model.getModelId())){
            Casualties modelMessage = this.getModelMessage(model.getModelId());
            if(PlatformObjectUtils.isNotEmpty(modelMessage)){
                model.setModelName(modelMessage.getModelName());
            }

        }
        if(PlatformObjectUtils.isEmpty(model)){
            return ResponseCreator.createSuccessResponse(model);
        }
        return ResponseCreator.createSuccessResponse(null);
    }

    public RestResponse getModelById(String id) {
        String url = fxfzypgUrl + "/casualty/getModelById?id="+id+"";

        return remoteService.getJCSJ(url,2,new JSONObject());
    }

    public List<AssessmentVulnerability> getAssessmentVulnerability(EvaluateParam evaluateParam) {
        return assessmentVulnerabilityRepository.getAssessmentVulnerability(evaluateParam);
    }

    public void saveAreaRatio(AreaRatio areaRatio) {
        String province = areaRatio.getProvince();
        String city = areaRatio.getCity();
        String county = areaRatio.getCounty();
        String userID = PlatformSessionContext.getUserID();

        getAllVulnerabilityList( province, city, county);
        AreaRatio areaRatio1 = areaRatioRepository.findByCondition
                (province, city, county, areaRatio.getStructureType());
        if (PlatformObjectUtils.isEmpty(areaRatio1)) {
            //保存
            areaRatio.setId(UUIDGenerator.getUUID());
            areaRatio.setCreateTime(new Date());
            areaRatio.setCreateUser(userID);
            areaRatioRepository.save(areaRatio);
        } else {
            //修改
            areaRatio.setId(areaRatio1.getId());
            areaRatio.setUpdateTime(new Date());
            areaRatio.setUpdateUser(userID);
            areaRatioRepository.update(areaRatio);
        }

    }


}
